package com.imooc.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imooc.mall.controller.vo.AddCategoryReq;
import com.imooc.mall.controller.vo.UpdateCategoryReq;
import com.imooc.mall.entity.Category;
import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.mapper.CategoryMapper;
import com.imooc.mall.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ZhaoJianHui
 * @since 2025-05-07
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    /**
     * 添加分类
     * @param addCategoryReq
     * @throws ImoocMallException
     */
    @Override
    public void add(AddCategoryReq addCategoryReq) {
        Category category = new Category();
        BeanUtils.copyProperties(addCategoryReq, category);
        //检查分类名是否已存在
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", addCategoryReq.getName());
        if (exists(queryWrapper)) {
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTS);
        }

        boolean save = save(category);
        if (!save) {
            throw new ImoocMallException(ImoocMallExceptionEnum.CREATE_FAILED);
        }
    }
    /**
     * 更新分类
     * @param updateCategoryReq
     */
    @Override
    public void upCategory(UpdateCategoryReq updateCategoryReq) {
        //检查分类名是否已存在
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", updateCategoryReq.getName());
        queryWrapper.ne("id", updateCategoryReq.getId());
        if (exists(queryWrapper)) {
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTS);
        }
        Category category = new Category();
        BeanUtils.copyProperties(updateCategoryReq, category);
        //更新分类
        boolean update = updateById(category);
        if (!update) {
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }
}
